<template>
    <div class="wrap">
        <div class="container">
            <TopBreadCrumb></TopBreadCrumb>
            <div class="user_center_content">
                <!-- 左侧菜单 -->
                <LeftNavMenu></LeftNavMenu>
                <!-- 左侧菜单结束 -->
                <!-- 右侧内容开始  -->
                <div v-loading="loading" class="right_user_content">
                    <div class="right-title border-bottom">
                        <div class="left">地址管理</div>
                        <div class="right text-blue" @click="CreateHandler()">新增收货地址</div>
                    </div>
                    <div class="enterprise-list address-list">
                        <!-- 发票列表 -->
                        <div class="enterprise-card" v-for="(item,index) in data.data" :key="index">
                            <div class="enterprise-card-cont">
                                <ul>
                                    <li><span>姓名：</span>{{item.consignee}}</li>
                                    <li><span>电话：</span>{{item.phone}}</li>
                                    <li><span>地址：</span>{{item.province_name + item.city_name + item.county_name + item.town_name + item.address}}</li>
                                    <li><span>邮编：</span>{{item.postal_code}}</li>
                                </ul>
                            </div> 
                            <div class="enterprise-card-foot">
                                <div class="checkbox">
                                    <el-checkbox true-label="1" false-label="0" v-model="item.is_default" @change="DefaultChangeHandler($event,item)"></el-checkbox> 设为默认收货地址
                                </div>
                                <div class="btn-group">
                                    <el-button class="btn-edit" @click="EditHanlder(item)">编辑</el-button>
                                    <el-button class="btn-detele" @click="DeleteHanlder(item)" plain>删除</el-button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <Custom-pagination :total="data.total" :page.sync="query.page" :pageSize.sync="query.pageSize" @pagination="doLoadData" :hidden="pageHidden"></Custom-pagination>
                </div>
                <!-- 右侧内容结束 -->
            </div>
        </div>

        <!-- 新增收货地址 开始 -->
        <el-dialog
            :title="title+'收货地址'"
            :close-on-click-modal="false"
            :visible.sync="dialogAddVisible"
            width="800px"
            top="6%">
            <div class="dialog-content add-address">
                <el-form ref="form"  :model="form" :rules="rules" :show-message="false" label-width="150px" label-position="left">
                    <el-form-item label="收货人"  prop="consignee">
                        <el-input v-model="form.consignee" placeholder="请输入收货人姓名" class="input-ww"></el-input>
                    </el-form-item>
                    <el-form-item  label="手机号"  prop="phone">
                        <el-input placeholder="请输入手机号" v-model="form.phone" class="input-with-select input-ww" >
                            <el-select v-model="form.prefix"  slot="prepend" placeholder="+86">
                                <el-option label="+86" value="+86"></el-option>
                                <!-- <el-option label="+00" value="+00"></el-option>
                                <el-option label="+01" value="+01"></el-option> -->
                            </el-select>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="邮政编码" prop="postal_code" >
                        <el-input v-model="form.postal_code" placeholder="请输入邮政编码" class="input-ww"></el-input>
                    </el-form-item>
                    <div class="form-item-block">
                        <el-form-item label="所在地区" prop="province" >
                            <el-select v-model="form.province_id" placeholder="省/直辖市" @change="ShengChangeHandler">
                                <el-option 
                                    v-for="(item,index) in provinceList"
                                    :key="index"
                                    :label="item.province_name" 
                                    :value="item.province_id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item ref="city" prop="city" label-width="10px">
                            <el-select v-model="form.city_id" placeholder="市" @change="CityChangeHandler">
                                <el-option 
                                    v-for="(item,index) in cityList"
                                    :key="index"
                                    :label="item.city_name" 
                                    :value="item.city_id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item ref="count">  
                            <el-select v-model="form.county_id" placeholder="区/县" @change="CountChangeHandler">
                                <el-option 
                                    v-for="(item,index) in countyList"
                                    :key="index"
                                    :label="item.county_name" 
                                    :value="item.county_id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item prop="town_id"  label-width="10px">
                            <el-select v-model="form.town_id"  placeholder="乡镇/街道">
                                <el-option 
                                    v-for="(item,index) in townList"
                                    :key="index"
                                    :label="item.town_name" 
                                    :value="item.town_id"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <el-form-item label="详细地址" required>
                        <el-input v-model="form.address" placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"></el-input>
                    </el-form-item>

                    <el-form-item>
                        <div class="checkbox">
                            <el-checkbox true-label="1" false-label="0" v-model="form.is_default"></el-checkbox>设置为默认地址
                        </div>
                    </el-form-item>
                    <el-form-item>
                        <el-button class="btn-main" @click="onSubmit">保存</el-button>
                    </el-form-item>

                </el-form>
            </div>
        </el-dialog>
        <!-- 新增收货地址 结束 -->
    </div>
</template>

<script>
import Vue from 'vue'
import $ from "jquery"
import CustomPagination from '../../components/CustomPagination.vue';
import api from "@/api/address"
import common from "@/api/common"
import { validatePhone } from "@/utils/common";
export default {
    components: { CustomPagination },
    data() {
        return {
            id:0,// 0默认为新增操作，若不为0则为更新
            loading:false,
            dialogAddVisible: false,
            dialogEditVisible: false,
            list:[],
            form:{
                prefix:"+86"
            }, // 默认收货地址
            provinceList:[], // 省的下拉框
            countyList:[],
            townList:[],
            cityList:[],
            query: {
                page: 1,
                pageSize:8
            },
            data: {
                data: [],
                total: 0
            },
            pageHidden: true,
            rules: {
                    consignee: [
                        { required: true, message: '请输入收件人', trigger: 'blur' },
                    ],
                    
                    phone: [
                        { required: true, message: '请输入收件人手机号', trigger: 'blur' },
                    ],
                    postal_code: [
                        { required: true, message: '请输入邮编', trigger: 'blur' },
                    ],
                    town_id: [
                        { required: true, message: '请输入公司地址', trigger: 'blur' },
                    ],
                    address: [
                        { required: true, message: '请输入详细地址', trigger: 'blur' },
                    ],
                },
            addressList: [
                {
                    name: "张三",
                    phone: "15915815715",
                    address: "北京市  朝阳区  朝阳路3巷200号",
                    postcode: "100020",
                },
                {
                    name: "李四",
                    phone: "15915815715",
                    address: " 上海市 浦东新区 贵龙园东方路1400号",
                    postcode: "100020",
                },
                {
                    name: "刘海",
                    phone: "15915815715",
                    address: "北京市  朝阳区  朝阳路3巷200号",
                    postcode: "100020",
                },
                {
                    name: "张柏",
                    phone: "15915815715",
                    address: "北京市  朝阳区  朝阳路3巷200号",
                    postcode: "100020",
                },
                {
                    name: "刘海",
                    phone: "15915815715",
                    address: "北京市  朝阳区  朝阳路3巷200号",
                    postcode: "100020",
                },
                {
                    name: "张柏",
                    phone: "15915815715",
                    address: "北京市  朝阳区  朝阳路3巷200号",
                    postcode: "100020",
                }

            ],
            num: 1,
            value:"",
            checked:"",
            title: "新增"
        };
    },
    created(){
        this.doLoadData()
    },
    methods: {
        doLoadData:function(){
            let _this = this;
            _this.loading = true
            api.GetAddressList(this.query)
                .then(res => {
                    this.data = res.data;
                    this.pageHidden = false;
                    if (this.query.pageSize >= this.data.total) {
                        this.pageHidden = true;
                    }
                    _this.loading = false
                });
        },
        CreateHandler:function(){
            let _this = this;
            _this.title="新增"
            if(_this.$refs.form){
                _this.$refs.form.resetFields();
            }
            // 新增
            this.form = {
                prefix:"+86"
            }; // 默认清空数据
            _this.dialogAddVisible = true // 打开弹窗
            //打开之前需要加载一次下拉框数据
            let input = {
                // type:"city"
            }
            this.InitProvinces(input)
            
        },
        EditHanlder:function(item){
            // 拿到可编辑的编号
            let _this = this;
            _this.title ="编辑"
            _this.addLoading = true;
            this.id = item.id
            let input = {
                id:item.id
            }
            api.GetAddressInfo(input)
                .then(res=>{
                    // 根据详情需要重新初始化一次数据
                    _this.EditInitProvinces(res.data)
            });
        },
        // 初始化区域结构（省市区街道） 只初始化第一级别
        InitProvinces:function(input){
            let _this = this;
            return new Promise((resolve, reject) => {
                common.GetAllProvinces(input)
                .then(res => {
                    switch(input.type){
                        case "city":
                        _this.cityList = res.data;
                        break;
                        case "county": // 区县
                        _this.countyList = res.data;
                        break;
                        case "town": // 乡镇
                        _this.townList = res.data;
                        break;
                        default:
                        _this.provinceList = res.data;
                        break;
                    } 
                    resolve();
                });
            });
        },
        // 编辑时候初始化全部
        EditInitProvinces:function(info){
            // 进行4级联合查询，根据info信息
            let _this = this
            
            let input = {}
            let inputcity = {
                        type:"city",
                        id:info.province_id
             }
            let inputcounty = {
                        type:"county",
                        id:info.city_id
                    }
            let inputtown = {
                        type:"town",
                        id:info.county_id
            }
            
            // 保证以下所有调用全部完成后在执行未来的操作
            Promise.all([
                 _this.InitProvinces(input),
                 _this.InitProvinces(inputcity),
                 _this.InitProvinces(inputcounty),
                 _this.InitProvinces(inputtown),
                ]).then(res => {
                    //_this.form = info

                    Vue.set(_this, 'form', info)
                    _this.addLoading = false;
                    _this.dialogAddVisible = true;
                    console.log("所有异步调用完成",info)
                })
        },
        // 省发生变化
        ShengChangeHandler:function(itm){
            // 加载市区事件
            let input = {
                type:"city",
                id:itm.toString()
            }

            this.DorpDownClear("");
            this.InitProvinces(input);
        },
        CityChangeHandler:function(itm){
             // 加载市区事件
             let input = {
                type:"county",
                id:itm
            }
            this.DorpDownClear("city");
            this.InitProvinces(input)
        },
        CountChangeHandler:function(itm){
             // 加载市区事件
             let input = {
                type:"town",
                id:itm
            }
            this.DorpDownClear("county");
            this.InitProvinces(input)
            
        },
        DorpDownClear:function(type){
                switch(type){
                    case "city":
                        this.countyList = [];
                        this.townList = [];
                       

                        Vue.set(this.form, 'county_id', '')
                        Vue.set(this.form, 'town_id', '')
                    break;
                    case "county": // 区县
                        this.townList = [];
                        
                        
                        Vue.set(this.form, 'town_id', '')
                    break;
                    default:
                        this.cityList   = [];
                        this.countyList = [];
                        this.townList   = [];
                        
                        Vue.set(this.form, 'city_id', '')
                        Vue.set(this.form, 'county_id', '')
                        Vue.set(this.form, 'town_id', '')
                    break;
                }
        },
        // 设置默认收货地址
        DefaultChangeHandler:function(e,item){
            let _this = this
            let input = {
                id:item.id,
                is_default:e
            }
            // 设置默认收货地址
            api.SetDefaultAddress(input)
                .then((res) =>{
                _this.doLoadData()    
            })
        },
        // 删除收货地址
        DeleteHanlder:function(item){


            let _this = this
            this.$confirm('是否删除地址?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let input = {
                id:item.id
                }
                // 设置默认收货地址
                api.DeleteAddress(input)
                    .then((res) =>{
                    _this.doLoadData()    
                })
            })
        },
        onSubmit: function(){
            // 提交之前验证一下
            var _this = this;

            _this.addLoading = true;
            _this.$refs.form.validate((valid) => {

            if (valid) {
                if (!validatePhone(_this.form.phone)) {
                    this.$message.error("请输入正确的手机号");
                    _this.addLoading = false;
                    return;
                }

                _this.form.id = _this.id
                api.CreateOrUpdateAddress(_this.form)
                    .then((res) =>{
                        console.log("提交后服务器返回的结果是:",_this.form)
                        console.log("提交之前的结果是:",_this.form)
                        
                        _this.$message.success("提交成功");
                        _this.addLoading = false;
                        _this.dialogAddVisible = false;
                        //_this.$refs.form.resetFields();
                        _this.id = 0 // 重置为新增
                        _this.doLoadData();

                        console.log("最终提交的结果是:",_this.form)

                }).catch((err) => {
                        _this.$message.error("提交失败");
                        _this.addLoading = false;
                })
            } else {
                _this.addLoading = false;
            }
            })       
        }
    },
    watch:{
    },
    mounted: function(){
        
    }

  };
</script>
<style>


</style>